﻿using DataManageSystem.Common;
using DataManageSystem.Exceptions;
using DataManageSystem.Models;
using DataManageSystem.Models.Dto;
using DataManageSystem.Services;
using DataManageSystem.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace DataManageSystem.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ScriptController : ControllerBase
    {
        private readonly ScriptService scriptService;

        public ScriptController(ScriptService scriptService)
        {
            this.scriptService = scriptService;
        }

        [HttpGet("selectScriptData")]
        public ObjectResult selectNoticeData(
            [FromQuery] int pageNum = 1,
            [FromQuery] int pageSize = 10,
            [FromQuery] string name = "",
            [FromQuery] string description = ""
        )
        {
            var res = scriptService.selectScriptData(pageNum, pageSize, name, description);
            return new ObjectResult(Result.Success(res));
        }

        [HttpPost("add")]
        public ObjectResult Add([FromBody] Script script)
        {
            scriptService.Add(script);
            return new ObjectResult(Result.Success("添加成功"));
        }

        [HttpPost("start/{id}")]
        public ObjectResult Start(int id)
        {
            var result = scriptService.start(id);
            return result ? new ObjectResult(Result.Success("启动成功")) : new ObjectResult(Result.Error("启动失败"));
        }



        [HttpPost("stop/{id}")]
        public ObjectResult Stop(int id)
        {
            var result = scriptService.stop(id);
            return result ? new ObjectResult(Result.Success("停止成功")) : new ObjectResult(Result.Error("停止失败"));
        }


        [HttpPut("update")]
        public ObjectResult Update([FromBody] Script script)
        {
            scriptService.update(script);
            return new ObjectResult(Result.Success("更新成功"));
        }

        [HttpDelete("delete/{id}")]
        public ObjectResult Delete(int id)
        {
            try
            {
                scriptService.Delete(id);
                return new ObjectResult(Result.Success("脚本删除成功"));
            }
            catch (ServiceException ex)
            {
                return new ObjectResult(Result.Error(ex.Message));
            }
            catch (Exception ex)
            {
                return new ObjectResult(Result.Error(ex.Message));
            }
        }
    }
}
